#!/bin/bash

# 自动清理 Windows 的换行符（\r），并重新运行一次干净版本
if file "$0" | grep -q CRLF; then
    echo "检测到脚本包含 Windows 换行符，正在转换为 Unix 格式..."
    sed -i 's/\r$//' "$0"
    exec bash "$0" "$@"
fi
echo "版本：v3.0"
# ANSI 颜色码定义
RED='\033[0;31m'    # 红色
GREEN='\033[0;32m'  # 绿色
BLUE='\033[0;34m'   # 蓝色
YELLOW='\033[1;33m' # 黄色
NC='\033[0m'        # 无颜色

# DNS 修复
resolve_dns_issue() {
    echo -e "${RED}检测到 DNS 解析错误，正在修复...${NC}"
    if ! grep -q "nameserver 8.8.8.8" /etc/resolv.conf; then
        echo "nameserver 8.8.8.8" | sudo tee -a /etc/resolv.conf
    fi
    if ! grep -q "nameserver 8.8.4.4" /etc/resolv.conf; then
        echo "nameserver 8.8.4.4" | sudo tee -a /etc/resolv.conf
    fi
    echo -e "${GREEN}DNS 解析错误已修复，继续执行...${NC}"
}

# 包装命令执行
execute_command() {
    local cmd="$1"
    eval "$cmd"
    if [ $? -ne 0 ]; then
        resolve_dns_issue
        eval "$cmd"
    fi
}

# 更换软件源函数
change_sources() {
    echo -e "${GREEN}请选择要更换的软件源：${NC}"
    echo -e "${GREEN}1. 网易源${NC}"
    echo -e "${GREEN}2. 阿里源${NC}"
    echo -e "${GREEN}3. 清华源${NC}"
    read -p "输入选择的编号 (1/2/3): " source_choice

    case "$source_choice" in
        1)
            NEW_SOURCES_URL="https://gitee.com/t88t/test/raw/master/debian12-163-sources.list"
            ;;
        2)
            NEW_SOURCES_URL="https://gitee.com/t88t/test/raw/master/debian12-aliyun-sources.list"
            ;;
        3)
            NEW_SOURCES_URL="https://gitee.com/t88t/test/raw/master/debian12-tsinghua-sources.list"
            ;;
        *)
            echo "无效的选择，请重新运行脚本并选择 1/2/3。"
            return
            ;;
    esac

    if [ ! -f /etc/apt/sources.list.bak ]; then
        echo "正在备份当前的 sources.list 到 sources.list.bak..."
        sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak
    else
        echo "已存在备份文件 sources.list.bak，跳过备份。"
    fi

    echo "正在下载新的 sources.list..."
    execute_command "wget -O /opt/debian-sources.list '$NEW_SOURCES_URL'"

    if [ $? -ne 0 ]; then
        echo "下载新的 sources.list 失败，请检查 URL 是否正确。"
        exit 1
    fi

    echo "正在替换当前的 sources.list..."
    sudo mv /opt/debian-sources.list /etc/apt/sources.list

    echo "正在更新软件包列表..."
    sudo apt update
    echo "软件源更换完成。"
    return_to_menu
}

# 更新 GitHub Hosts
update_github_ip() {
  echo -e "${YELLOW}正在更新 GitHub 的 IP 地址...${NC}"
  GITHUB_IPS=$(wget -qO- https://api.github.com/meta | jq -r '.git[]')
  if [[ -z "$GITHUB_IPS" ]]; then
    echo -e "${RED}无法获取 GitHub 最新 IP，跳过更新 /etc/hosts${NC}"
    return
  fi
  sed -i "/github.com/d" /etc/hosts
  for ip in $GITHUB_IPS; do
    echo "$ip github.com" >> /etc/hosts
    echo "$ip objects.githubusercontent.com" >> /etc/hosts
    echo "$ip raw.githubusercontent.com" >> /etc/hosts
  done
  echo -e "${GREEN}GitHub 的 IP 地址已更新！${NC}"
  return_to_menu
}

# 安装 Docker
install_docker() {
    echo "更新依赖..."
    sudo apt update

    echo "安装必要依赖..."
    sudo apt install -y curl software-properties-common

    echo "添加官方密钥..."
    curl -fsSL https://download.docker.com/linux/debian/gpg | sudo apt-key add -

    echo "添加 Docker 源..."
    sudo add-apt-repository -y "https://download.docker.com/linux/debian $(lsb_release -cs) stable"

    echo "安装 Docker..."
    sudo apt install -y docker-ce docker-ce-cli containerd.io docker-compose

    echo "启动并设置 Docker 开机自启..."
    sudo systemctl start docker
    sudo systemctl enable docker

    echo "Docker 安装完成："
    docker version
    docker-compose version

    sudo systemctl daemon-reexec
    sudo systemctl restart docker
    return_to_menu
}

# 安装 SRT（自动安装脚本）
install_srt() {
    echo -e "${GREEN}正在执行自动安装聚合 VPS 端脚本...${NC}"
    wget -qO- https://gitee.com/t88t/omr_-vps_-auto/raw/master/Auto_Omr_vps.sh | bash
    echo -e "${YELLOW}脚本执行完畢，如需重启请手动操作。${NC}"
    return_to_menu
}


# 安装 SRS（略）
install_srs() {
    echo -e "${GREEN}请选择安装方式：${NC}"
    echo -e "${GREEN}1. Docker 版(不适合聚合vps端安装)${NC}"
    echo -e "${GREEN}2. 编译版${NC}"
    read -p "输入选择的编号 (1/2): " srs_choice

    case "$srs_choice" in
        1)
            if ! command -v docker &> /dev/null; then
                echo -e "${RED}Docker 未安装，正在安装 Docker...${NC}"
                install_docker
            fi
            docker run --restart always -d -it --name oryx -v $HOME/data:/data \
            -p 2021:2022 -p 443:2443 -p 1935:1935 -p 8000:8000/udp -p 10080:10080/udp \
            registry.cn-hangzhou.aliyuncs.com/ossrs/oryx:5
            ;;
        2)
            for pkg in git gcc g++ make automake tclsh cmake pkg-config; do
                if ! command -v "$pkg" &> /dev/null; then
                    sudo apt-get install -y "$pkg"
                fi
            done
            git clone -b develop https://gitee.com/ossrs/srs.git
            cd srs/trunk
            ./configure
            make
            ./objs/srs -c conf/srs.conf
            ;;
        *)
            echo "无效的选择。请重新选择。"
            ;;
    esac
    return_to_menu
}

# 开启 root 登录
enable_root_login() {
    echo -e "${GREEN}正在开启 root 登录功能...${NC}"
    bash <(wget -qO- https://gitee.com/tttt/omr_-vps_-auto/raw/master/root.sh)
    echo -e "${YELLOW}执行完毕，请手动验证 SSH 是否允许 root 登录。${NC}"
    return_to_menu
}

# 主菜单
return_to_menu() {
    echo -e "${GREEN}请选择操作：${NC}"
    echo -e "${GREEN}1. 更换软件源（选择3自带该功能）${NC}"
    echo -e "${GREEN}2. 修改 HOST（选择3自带该功能）${NC}"
    echo -e "${GREEN}3. 安装 聚合VPS端（调用Omr_VPS_Auto）${NC}"
    echo -e "${GREEN}4. 安装 SRS（编译版跟docker版）${NC}"
    echo -e "${GREEN}5. 开启 root 登录${NC}"
    echo -e "${GREEN}0. 退出${NC}"
    read -p "输入选择的编号 (0-5): " choice

    case "$choice" in
        1) change_sources ;;
        2) update_github_ip ;;
        3) install_srt ;;
        4) install_srs ;;
        5) enable_root_login ;;
        0) echo "退出脚本。" && exit 0 ;;
        *) echo "无效选择。" && return_to_menu ;;
    esac
}

main() {
    if [ -t 0 ]; then
        return_to_menu
    else
        exec </dev/tty
        return_to_menu
    fi
}

main
